/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { data, follow } from "@mall/api-services"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import { RouteComponentProps, withRouter } from "react-router"
import Divider from "../components/divider"
import Flex from "../components/flex"
import NavBar from "../components/navbar"
import ProductPrice from "../components/product/product-price"
import Icon from "../icon"

import "./follow-products.scss"

interface DisplayFollowProductProps extends RouteComponentProps {
  followProduct: follow.FollowProduct
}

function DisplayFollowProductComponent(props: DisplayFollowProductProps) {

  const { history, followProduct } = props

  return (
    <Flex className="display-follow-product"
          onClick={() => history.push(`/products/${followProduct.id}`)}>
      <div className="product-image">
        <img src={followProduct.imageUrl} alt=""/>
      </div>
      <Flex direction="column" justifyContent="space-around">
        <span>{followProduct.name}</span>
        <ProductPrice price={100.02} size={16}/>
      </Flex>
      <Divider/>
    </Flex>
  )
}

const DisplayFollowProduct = withRouter(DisplayFollowProductComponent)

interface FollowProductListProps {
  customerId: string;
}

function FollowProductList(props: FollowProductListProps) {
  const { customerId } = props
  const [pageFollowProducts, setPageFollowProducts] = useState(data.PageList.empty() as data.PageList<follow.FollowProduct>)
  const { elements } = pageFollowProducts

  useEffect(() => {
    follow.FollowServiceV1.getFollowingProducts().list().then(setPageFollowProducts)
  }, [customerId])

  return (
    <div className="follow-product-list">
      {_.map(elements, followProduct =>
        <DisplayFollowProduct key={followProduct.id} followProduct={followProduct}/>)}
    </div>
  )
}

interface FollowProductsProps extends RouteComponentProps {

}

function FollowProducts(props: FollowProductsProps) {
  const { history, match } = props
  const customerId = match.params["customer_id"]
  return (
    <div className="follow-products">
      <NavBar left={<Icon type="left" onClick={() => history.goBack()}/>}
              className="follow-products-nav-bar">关注的商品</NavBar>
      <FollowProductList customerId={customerId}/>
    </div>
  )
}

export default withRouter(FollowProducts)
